package com.hxkj.controller;

import com.github.pagehelper.PageInfo;
import com.hxkj.client.service.UserLoginHistoryServiceClient;
import com.hxkj.domain.enums.UserExceptionEnum;
import com.hxkj.domain.po.Token;
import com.hxkj.domain.po.UserLoginHistory;
import com.hxkj.service.TokenService;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.exception.CustomMessageException;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.to.PageTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * created by kezhijie on 2018/8/31 17:10.
 * email to kezhijie@hxoss.com
 */
@RestController
@RequestMapping("loginHistory")
public class UserLoginHistoryController {

    @Autowired
    private UserLoginHistoryServiceClient userLoginHistoryServiceClient;
    @Autowired
    private TokenService tokenService;

    @PostMapping("get")
    public PageInfo get(@ModelAttribute UserLoginHistory userLoginHistory, PageTo pageParam, HttpServletRequest request) throws Exception {
        ParameterDataStruct<UserLoginHistory> parameterDataStruct = new ParameterDataStruct<>();


        if (Objects.isNull(userLoginHistory) || StringUtils.isEmpty(userLoginHistory.getUserId())) {
            userLoginHistory = new UserLoginHistory();
            userLoginHistory.setUserId(getUserId(request));
        }

        parameterDataStruct.setData(userLoginHistory);
        parameterDataStruct.setPageTo(pageParam);

        ResultDataStruct<PageInfo> resultDataStruct = userLoginHistoryServiceClient.get(parameterDataStruct);

        if (resultDataStruct.getCode() == 500)
            throw new CustomMessageException(resultDataStruct.getMessage());
        if (resultDataStruct.getCode() != 200)
            throw new CustomException(UserExceptionEnum.getEnumByCode(resultDataStruct.getCode()));

        return resultDataStruct.getData();
    }

    private String getUserId(HttpServletRequest request) throws Exception {
        String token = request.getHeader("accessToken");
        ResultDataStruct<Token> resultDataStruct = tokenService.validate(token);

        if (resultDataStruct.getCode() != 200)
            throw new CustomException(UserExceptionEnum.getEnumByCode(resultDataStruct.getCode()));

        return resultDataStruct.getData().getUserId();
    }
}
